/**
 * Description
 *
 * Creation Date 20/12/2017
 * @author Candy
 */
import React, { Component } from 'react'
import {

	AppRegistry,

	StyleSheet,

	Text,

	View,

	AsyncStorage,

	TouchableHighlight,

} from 'react-native';

var STORAGE_KEY_ONE = '@AsyncStorageDemo:key_one';

var STORAGE_KEY_MESSAGE = '@AsyncStorageDemo:key_message';

//简单封装一个组件

class CustomButton extends Component {

	render()
	{

		return(

			<TouchableHighlight

				style={styles.button}

				underlayColor="#a5a5a5"

				onPress={this.props.onPress}>

				<Text
					style={styles.buttonText}>{this.props.text}</Text>

			</TouchableHighlight>

		);

	}

}

export default class AsyncStorageDemo extends Component {

	constructor(props){

		super(props);

		this.state={

			messages:[],

		};

	}

	//组件挂载之后回调方法

	componentDidMount(){

		this._loadInitialState().done();

	}

	//初始化数据-默认从AsyncStorage中获取数据

	async _loadInitialState(){

		try{

			var value= await AsyncStorage.getItem(STORAGE_KEY_ONE);
			 // value += await AsyncStorage.getItem(STORAGE_KEY_MESSAGE);

			if(value!=null){
				console.log(value)
				this._appendMessage('从存储中获取到数据为:'+value);

			}else{

				this._appendMessage('存储中无数据,初始化为空数据');

			}

		}catch(error){

			this._appendMessage('AsyncStorage错误'+error.message);

		}

	}

	//进行储存数据_ONE

	async _saveValue_One(){
		let product = {
			1:{
				id: 1,
				name: 'test',
				price: '12',
				num: 1
			},
			total: 200
		};
		product = JSON.stringify(product)

		try{

			await AsyncStorage.setItem(STORAGE_KEY_ONE, product);
			// await AsyncStorage.setItem(STORAGE_KEY_MESSAGE,'store');
			console.log('yes')

			this._appendMessage('保存到存储的数据为:'+'candy');

		}catch(error){

			this._appendMessage('AsyncStorage错误'+error.message);

		}

	}

	//进行存储数据删除_ONE

	async _removeValue_One(){

		try{

			await AsyncStorage.removeItem(STORAGE_KEY_ONE);
			await AsyncStorage.removeItem(STORAGE_KEY_MESSAGE);

			this._appendMessage('数据删除成功...');

		}catch(error){

			this._appendMessage('AsyncStorage错误'+error.message);

		}

	}

	//进行把message信息添加到messages数组中

	_appendMessage(message){

		this.setState({messages:this.state.messages.concat(message)});

	}

	render()
	{

		return(

			<View>

				<Text
					style={styles.welcome}>

					AsyncStorage使用实例

				</Text>

				<CustomButton
					text='点击存储数据_candy'

					onPress={this._saveValue_One}/>

				<CustomButton
					text='点击删除数据'

					onPress={this._removeValue_One}/>

				<Text
					style={styles.content}>信息为:</Text>

				{this.state.messages.map((m) => <Text style={styles.content} key={m}>{m}</Text>)}

			</View>

		);

	}

}

const styles = StyleSheet.create({

		welcome:
			{

				fontSize: 14,

				textAlign: 'left',

				margin: 10,

			},

		content:{

			fontSize: 13,

			textAlign: 'left',

			margin: 10,

		},

		button:
			{

				margin:5,

				backgroundColor: 'white',

				padding: 15,

				borderBottomWidth: StyleSheet.hairlineWidth,

				borderBottomColor: '#cdcdcd',

			}

	});